﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TasksUI
{
    public partial class WsSyncConfig : Form
    {
        public WsSyncConfig()
        {
            InitializeComponent();
        }

        public WsSyncConfig(TasksModel.TaskLibrary library)
            : this()
        {
            TasksModel.WebServiceSynchSettings set = library.SynchSettings as TasksModel.WebServiceSynchSettings;
            if (set == null)
                _settings = new TasksModel.WebServiceSynchSettings();
            else
            {
                _settings = new TasksModel.WebServiceSynchSettings(set);
                // fill
                tbUrl.Text = _settings.Url;
                bConnect.Enabled = tbUrl.Text.Length > 0;
                if (_settings.IsConfigured)
                    bApply.Enabled = true;
            }
        }

        private TasksModel.WebServiceSynchSettings _settings;

        public static void Show(TasksModel.TaskLibrary library)
        {
            using (WsSyncConfig f = new WsSyncConfig(library))
            {
                if (f.ShowDialog(Form.ActiveForm) == DialogResult.OK)
                    library.SynchSettings = f._settings;
            }
        }

        private void bConnect_Click(object sender, EventArgs e)
        {
            tbUrl.Enabled = false;
            bApply.Enabled = false;
            try
            {
                TasksUI.Helpers.WsHelper g = new TasksUI.Helpers.WsHelper();
                g.Url = tbUrl.Text;
                // connect
                if (g.Connect(null, null))
                {
                    tbUrl.Enabled = true;
                    bApply.Enabled = true;
                }
            }
            catch (SystemException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bApply_Click(object sender, EventArgs e)
        {
            if (tbUrl.Text.Length > 6)
            {
                _settings.Url = tbUrl.Text;
                if (_settings.IsConfigured)
                    DialogResult = DialogResult.OK;
            }
        }

        private void tbUrl_TextChanged(object sender, EventArgs e)
        {
            bConnect.Enabled = tbUrl.Text.Length > 0;
        }
    }
}